/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
var geo;
var map;
var bars = [
    {name: "Bar Circus", address: "Olav Tryggvasons gate 27, 7011 Trondheim", age_limit: "20", info: "Bar Circus is a rock bar located in the heart of Trondheim."},
    {name: "Raus", address: "Nordre gate 21, 7010 Trondheim", age_limit: "23", info: "Raus is a lounge/bar with a calm atmosphere and some of the best drinks in town."},
    {name: "Brukbar", age_limit: "20", address: "Kongens gate 19, 7012 Trondheim", info: "Brukbar is the most popular hipster bar in Norway"},
    {name: "Trondheim Mikrobryggeri", address: "Prinsens gate 39, 7011 Trondheim", age_limit: "20", info: "Trondheim Mikrobryggeri has a long tradition in brewing their own beer."},
    {name: "Den Gode Nabo", address: "Øvre Bakklandet 66, 7013 Trondheim", age_limit: "18", info: "Located right by the bridge 'bybroen' is Den Gode Nabo, known for their expertise in beer."},
    {name: "Nova Hotell Kurs og Konferanse", address: "Cicignons plass, 7011 Trondheim", age_limit: "20", info: "Nova hotell is located in the center of Trondheim."},
    {name: "Bari", address: "Munkegata 25, 7011 Trondheim", age_limit: "20", info: "Bari is a little bar located under the restaurant Frati."},
    {name: "Nattergalen", address: "Olav Tryggvasons gate 33, 7011 Trondheim", age_limit: "20", info: "Nattergalen is most famous for their weekly student quiz."},
    {name: "Havfruen", address: "Kjøpmannsgata 7, 7013 Trondheim", age_limit: "20", info: "Havfruen is located in kjøpmannsgata."},
    {name: "Ramp", address: "Strandveien 25a, 7042 Trondheim", age_limit: "20", info: "Ramp is a cafe/restaurant in Strandveien."},
    {name: "Cafe Løkka", address: "Dokkgata 8, 7014 Trondheim", age_limit: "20", info: "A nice, little cafe located at Solsiden."},
    {name: "Restaurant Kommandanten", address: "Kristiansten Festning, 7016 Trondheim", age_limit: "20", info: "The restaurant/pub Kommandanten is located inside Kristiansten festning."},
    {name: "Olavs Pub og Spiseri", address: "Olav Tryggvasons gate 5, 7011 Trondheim", age_limit: "20", info: "Known for their weekly stand up comedies every thursday."},
    {name: "Cafe Vivaldi", address: "Thomas Angells gate 10b, 7011 Trondheim", age_limit: "20", info: "Cafe Vivaldi needs more info."},
    {name: "Supa", address: "Kongens gate 19, 7012 Trondheim", age_limit: "20", info: "Supa is a night club located in the basement of Brukbar."},
    {name: "Cafe Dublin", address: "Kongens gate 15, 7013 Trondheim", age_limit: "20", info: "A cozy irish pub who often plays live music."},
    {name: "Kieglekroa", address: "Kongens gate 30, 7012 Trondheim", age_limit: "20", info: "Kieglekroa needs more info."},
    {name: "Kos Bar og Lounge", address: "Carl Johans gate 8, 7010 Trondheim", age_limit: "21", info: "Kos bar og lounge is known for their drinks and good atmosphere."},
    {name: "Three Lions Pub", address: "Brattørgata 10, 7010 Trondheim", age_limit: "20", info: "This english owned sportsbar is always crowded on match day."},
    {name: "Lille London", address: "Carl Johans gate 10, 7010 Trondheim", age_limit: "20", info: "This classic english pub offers a variety of draught, pool and sport on TV."},
    {name: "Bar 3B", address: "Brattørgata 3B, 7010 Trondheim", age_limit: "20", info: "This bar plays rock and offers pool and dart."},
    {name: "Frida", address: "Fjordgata 15, 7010 Trondheim", age_limit: "18", info: "A mexican restaurant with good food and lots of tequila."},
    {name: "Bobbys Bar", address: "Carl Johans gate, 7010 Trondheim", age_limit: "20", info: "Bobbys Bar is always clogged with people drinking from AM to PM."},
    {name: "DownTown", address: "Nordre gate 28, 7010 Trondheim", age_limit: "20", info: "DownTown has a piano bar in forst floor and a disco upstairs."},
    {name: "Dreams Showbar", address: "Munkegata 68B, 7011 Trondheim", age_limit: "20", info: "Trondheims only strip club."},
    {name: "Byåsen Pub", address: "Bøckmans veg 110, 7022 Trondheim", age_limit: "20", info: "A little pub located at Byåsen."},
    {name: "Macbeth Scottish Pub", address: "Søndre gate 22B, 7010 Trondheim", age_limit: "20", info: "A scottish pub with a variety of draught beer."},
    {name: "Fru Lundgreens Pub", address: "Kjøpmannsgata 50, 7010 Trondheim", age_limit: "20", info: "Come and rock out in our basement."},
    {name: "Studentersamfundet", address: "Elgesetergate 1, 7030 Trondheim", age_limit: "20", info: "Owned and ran by students at NTNU."},
    {name: "Møllenberg Vertshus", address: "Rosenborg gate 12A, 7014 Trondheim", age_limit: "20", info: "A cozy little pub just outside Trondheim center."},
    {name: "Daniel På hjørnet", address: "Kjøpmannsgata 34, 7011 Trondheim", age_limit: "20", info: "This bar is usually visited by their regular clients."},
    {name: "D12", address: "Dronningens gate 12, 7011 Trondheim", age_limit: "20", info: "With piano bar and discotheque, this night club offers something for all ages."},
    {name: "Blæst", address: "Tmv-kaia 17, 7014 Trondheim", age_limit: "20", info: "A bar located at beautiful Solsiden. Blæst often offers live music"},
    {name: "Karma Lounge Club", address: "Kongens gate 8, 7011 Trondheim", age_limit: "18", info: "One of the few clubs accessible by people under 20."},
    {name: "Club Gossip", address: "Fjordgata 15, 7010 Trondheim", age_limit: "20", info: "The night club where you'll find the most reality tv- celebrities."},
    {name: "Mormors Stue", address: "Nedre Enkeltskillingsveita 2, 7011 Trondheim", age_limit: "18", info: "This old house really lives up to it's name 'Grandma's living room'."},
    {name: "Studio 26", address: "Nordre gate 26, 7010 Trondheim", age_limit: "20", info: "Studio 26 is one of Trondheims largest night clubs."},
    {name: "Vega", address: "Thomas Angells gate 12, 7010 Trondheim", age_limit: "20", info: "A little more classy night club with dress code and champagne on ice."},
    {name: "Barmuda", address: "Tmv-kaia 9, 7014 Trondheim", age_limit: "21", info: "A two floors bar located on Solsiden. One of the most popular places to be on sundays when the offer cheap Cava"}
];
function initialize() {
     geo = new google.maps.Geocoder();
    var latLng = new google.maps.LatLng(-34.397, 150.644);
    var mapOptions = {
      center: latLng,
      zoom: 14
    };
    map = new google.maps.Map(document.getElementById("map-canvas"),
        mapOptions);
        
    // Try HTML5 geolocation
    if(navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
        var pos = new google.maps.LatLng(position.coords.latitude,
                                         position.coords.longitude);
                                         
        var marker = new google.maps.Marker({
            map: map,
            position: pos,
            title: "Your position"
        });
        console.log("lengde" + bars.length);
        var counter = 0;
        var counterObj = {};
        var length = bars.length;
        
        for(var i=0; i<bars.length; i++){
            if(i % 10 === 0){
                var name = counter;
                counterObj[name] = [];
                counter++;
            }
            counterObj[name].push(bars[i]);
        }
        var size = Object.size(counterObj);
        console.log(counterObj);
        
        for(var i=0; i<size; i++){
            (function(number){
                console.log("kjører" + number);
                setTimeout(function(){
                    for(var j=0; j<counterObj[number].length; j++){
                        $.when(getGeoLocation(counterObj[number][j])).then(
                            function(returnItems){
                                var barPos = returnItems;
                                var barLatLng = new google.maps.LatLng(barPos.location.k, barPos.location.A);
                                new google.maps.Marker({
                                    map: map,
                                    position: barLatLng,
                                    title: barPos.name,
                                    icon: "resources/images/beer-icon-medium.png"
                                });
                            }
                        ); 
                    }
                },200); 
            })(i);
        }
        
        var iw = new google.maps.InfoWindow({
            content: this.title
        });
        
        google.maps.event.addListener(marker, "click", function (e) { iw.open(map, this); });

        
        map.setCenter(pos);
      }, function() {
        handleNoGeolocation(true);
      });
    } else {
      // Browser doesn't support Geolocation
      handleNoGeolocation(false);
    }
}

Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

function handleNoGeolocation(errorFlag) {
  if (errorFlag) {
    var content = 'Error: The Geolocation service failed.';
  } else {
    var content = 'Error: Your browser doesn\'t support geolocation.';
  }

  var options = {
    map: map,
    position: new google.maps.LatLng(60, 105),
    content: content
  };

  var infowindow = new google.maps.InfoWindow(options);
  map.setCenter(options.position);
}

var geocoder = new google.maps.Geocoder();
 
 
    var progress = 0;
 
function getGeoLocation(addressData){
    var dfd = new $.Deferred();
    geocoder.geocode({
        'address': addressData.address
    }, function (results, status) {
        if (status === google.maps.GeocoderStatus.OK) {
            //Returns the whole parameter plus the LatLng-location
            var result = addressData;
            result.location = results[0].geometry.location;
           //progress++;
            dfd.resolve(result);
        }
        else if(status === google.maps.GeocoderStatus.OVER_QUERY_LIMIT){
            setTimeout(function(){
                //getGeoLocation(addressData); 
                console.log("OVER QUERY LIMIT");
               dfd.reject(addressData.address);
            },500);
        }
        else {
            //progress++;
             console.log("error in the geocoder method");
             dfd.reject(addressData.address);
        }
    });                          
    return dfd.promise();
}

//google.maps.event.addDomListener(window, 'load', initialize);